package com.esunrising.esungsc.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.dto.MyRequestBody;
import com.esunrising.esungsc.dto.Result;
import com.esunrising.esungsc.exception.ESUNException;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/index")
public class IndexController {

    @Resource
    private StringEncryptor myEncryptorBean;
    @GetMapping("/index")
    public String index(){
        return "Hello, world!";
    }

    @GetMapping("/encode")
    public String encode(@RequestParam("str") String str){
        return myEncryptorBean.encrypt(str);
    }

    @GetMapping("/decode")
    public String decode(String str){
        return myEncryptorBean.decrypt(str);
    }

    @GetMapping("/json")
    public Result<Map<String, String>> getJson(@RequestParam("str") String str){
        return Result.ok(Map.of("str", str));
    }

    @PostMapping("/testHeader")
    public Result<Map<String, String>> testHeader(HttpServletRequest request, @RequestParam("str") String str){
        System.out.println("request:");
        System.out.println(request);
        System.out.println("Authorization:"+request.getHeader("Authorization"));
        return Result.ok(Map.of("str", str));
    }

    @PostMapping("/testBody")
    public Result<Map<String, String>> testBody(String str, @RequestBody MyRequestBody requestBody){
        System.out.println("requestBody:");
        System.out.println(requestBody);
//        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>)requestBody;
//        System.out.println("page:"+map.get("page"));
        System.out.println("page:"+requestBody.getPage());
        System.out.println("pageSize:"+requestBody.getPageSize());
        return Result.ok(Map.of("str", str));
    }

    @PostMapping("/testHeadAndBody")
    public Result<Map<String, String>> testHeadAndBody(HttpServletRequest request, String str, @RequestBody MyRequestBody requestBody){
        System.out.println("request:");
        System.out.println(request);
        System.out.println("Authorization:"+request.getHeader("Authorization"));
        System.out.println("requestBody:");
        System.out.println(requestBody);
//        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>)requestBody;
//        System.out.println("page:"+map.get("page"));
        System.out.println("page:"+requestBody.getPage());
        System.out.println("pageSize:"+requestBody.getPageSize());
        return Result.ok(Map.of("str", str));
    }

    /**
     * 读取resource文件夹下的JSON文件
     * @param fileName 文件名，相对resource文件夹的路径，如：/test/json/voucherData.json
     * @return JSONObject json文件内容解析后的json对象
     */
    private JSONObject getFileJson(String fileName){

        // 获取JSON
        InputStream resourceAsStream = this.getClass().getResourceAsStream(fileName);
        if(resourceAsStream == null){
            throw new ESUNException("未找到文件:"+fileName);
        }
        try (Reader reader = new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)){
            int ch;
            StringBuilder sb = new StringBuilder();
            while((ch= reader.read())!=-1){
                sb.append((char) ch);
            }
            String jsonStr = sb.toString();
            return JSON.parseObject(jsonStr);
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/getVoucherList")
    public JSONObject testVoucher(HttpServletRequest request, String str, @RequestBody MyRequestBody requestBody){

        System.out.println("Authorization:"+request.getHeader("Authorization"));
        System.out.println(requestBody.getPage());
        if(Integer.parseInt(requestBody.getPage()) > 1){
            return null;
        }
        return getFileJson("/test/json/voucherData.json");
    }

    @PostMapping("/getCustomItem")
    public JSONObject testCustomItem(HttpServletRequest request, String str, MyRequestBody requestBody){

        System.out.println("Authorization:"+request.getHeader("Authorization"));
        // 获取JSON
        return getFileJson("/test/json/customItemData.json");
    }

    @PostMapping("/getBfLedger")
    public JSONObject testBfLedger(HttpServletRequest request, String str, MyRequestBody requestBody){

        System.out.println("Authorization:"+request.getHeader("Authorization"));
        // 获取JSON
        return getFileJson("/test/json/bfLedgerData.json");
    }

    @PostMapping("/getBfChartOfAccount")
    public JSONObject testBfChartOfAccount(HttpServletRequest request, String str, MyRequestBody requestBody){

        System.out.println("Authorization:"+request.getHeader("Authorization"));
        // 获取JSON
        return getFileJson("/test/json/bfChartOfAccount.json");
    }

    @PostMapping("/getAccountTitle")
    public JSONObject testgetAccountTitle(HttpServletRequest request, String str, MyRequestBody requestBody){
        System.out.println("Authorization:"+request.getHeader("Authorization"));

        File file = new File("D:\\work\\esungsc\\doc\\accountTitle.json");

        try (Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8")) {
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read())!= -1) {
                sb.append((char) ch);
            }
            String jsonStr = sb.toString();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            return jsonObject;

        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }


    @PostMapping("/getCustomItemCategory")
    public  JSONObject testgetCustomItemCategory(HttpServletRequest request , String str, MyRequestBody requestBody){
        System.out.println("Authorization:"+request.getHeader("Authorization"));

        File file = new File("D:\\work\\esungsc\\doc\\customItemCategory.json");

        try(Reader reader = new InputStreamReader(new FileInputStream(file))) {
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read())!= -1) {
                sb.append((char) ch);
            }
            String jsonStr = sb.toString();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            return jsonObject;

        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }


    @PostMapping("/getCustomItems")
    public JSONObject testgetCustomItems(HttpServletRequest request , String str, MyRequestBody requestBody){
        System.out.println("Authorization:"+request.getHeader("Authorization"));
        File file = new File("D:\\work\\esungsc\\doc\\customItems.json");
        try(Reader reader = new InputStreamReader(new FileInputStream(file))){
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read())!= -1) {
                sb.append((char) ch);
            }
            String jsonStr = sb.toString();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            return jsonObject;

        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}
